<template>
  <div class="app-container">
    <!-- 授权统计卡片 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon primary">
              <el-icon :size="32"><Document /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-title">总授权数</div>
              <div class="stat-value">{{ licenseStats.total }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon success">
              <el-icon :size="32"><CircleCheck /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-title">正常授权</div>
              <div class="stat-value">{{ licenseStats.normal }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon warning">
              <el-icon :size="32"><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-title">即将过期</div>
              <div class="stat-value">{{ licenseStats.expiring }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon danger">
              <el-icon :size="32"><WarningFilled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-title">已过期</div>
              <div class="stat-value">{{ licenseStats.expired }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 验证统计 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日验证统计</span>
            </div>
          </template>
          <el-row :gutter="16">
            <el-col :span="6">
              <div class="mini-stat">
                <div class="label">总验证</div>
                <div class="value">{{ logStats.today.total }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="mini-stat">
                <div class="label success">成功</div>
                <div class="value success">{{ logStats.today.success }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="mini-stat">
                <div class="label danger">失败</div>
                <div class="value danger">{{ logStats.today.fail }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="mini-stat">
                <div class="label warning">异常</div>
                <div class="value warning">{{ logStats.today.abnormal }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>本月验证统计</span>
            </div>
          </template>
          <el-row :gutter="16">
            <el-col :span="6">
              <div class="mini-stat">
                <div class="label">总验证</div>
                <div class="value">{{ logStats.month.total }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="mini-stat">
                <div class="label success">成功</div>
                <div class="value success">{{ logStats.month.success }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="mini-stat">
                <div class="label danger">失败</div>
                <div class="value danger">{{ logStats.month.fail }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="mini-stat">
                <div class="label warning">异常</div>
                <div class="value warning">{{ logStats.month.abnormal }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 验证趋势图表 -->
    <el-card shadow="hover" class="mb-20">
      <template #header>
        <div class="card-header">
          <span>近7天验证趋势</span>
        </div>
      </template>
      <div ref="trendChart" style="height: 300px;"></div>
    </el-card>

    <!-- 错误类型统计
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>近30天错误类型统计</span>
        </div>
      </template>
      <div ref="errorChart" style="height: 300px;"></div>
    </el-card> -->
  </div>
</template>

<script setup name="Index">
import { ref, onMounted, getCurrentInstance, nextTick } from 'vue'
import { getStatistics } from '@/api/license/log'
import { listLicense } from '@/api/license/license'
import * as echarts from 'echarts'

const { proxy } = getCurrentInstance()

// 数据
const licenseStats = ref({
  total: 0,
  normal: 0,
  expiring: 0,
  expired: 0
})

const logStats = ref({
  today: { total: 0, success: 0, fail: 0, abnormal: 0 },
  month: { total: 0, success: 0, fail: 0, abnormal: 0 },
  trend: [],
  errors: []
})

const trendChart = ref(null)
const errorChart = ref(null)

// 加载授权统计
async function loadLicenseStats() {
  try {
    const res = await listLicense({ page: 1, limit: 1000 })
    if (res && res.list) {
      const list = res.list
      licenseStats.value.total = list.length
      
      // 统计各状态数量
      const now = Date.now() / 1000
      const thirtyDays = 30 * 24 * 60 * 60
      
      list.forEach(item => {
        if (item.status === 1) {
          licenseStats.value.normal++
          // 判断是否即将过期（30天内）
          if (item.end_date) {
            const endTime = new Date(item.end_date).getTime() / 1000
            if (endTime > now && endTime - now < thirtyDays) {
              licenseStats.value.expiring++
            }
          }
        } else if (item.status === 2 || item.is_expired) {
          licenseStats.value.expired++
        }
      })
    }
  } catch (error) {
    console.error('加载授权统计失败:', error)
  }
}

// 加载验证日志统计
async function loadLogStats() {
  try {
    const res = await getStatistics()
    if (res) {
      logStats.value = {
        today: res.today || { total: 0, success: 0, fail: 0, abnormal: 0 },
        month: res.month || { total: 0, success: 0, fail: 0, abnormal: 0 },
        trend: res.trend || [],
        errors: res.errors || []
      }
      
      // 渲染图表
      await nextTick()
      renderTrendChart()
      renderErrorChart()
    }
  } catch (error) {
    console.error('加载日志统计失败:', error)
  }
}

// 渲染趋势图表
function renderTrendChart() {
  if (!trendChart.value) return
  
  const chart = echarts.init(trendChart.value)
  const dates = logStats.value.trend.map(item => item.date)
  const totalData = logStats.value.trend.map(item => item.total)
  const successData = logStats.value.trend.map(item => item.success)
  const failData = logStats.value.trend.map(item => item.fail)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['总验证', '成功', '失败']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '总验证',
        type: 'line',
        data: totalData,
        smooth: true,
        itemStyle: { color: '#409EFF' }
      },
      {
        name: '成功',
        type: 'line',
        data: successData,
        smooth: true,
        itemStyle: { color: '#67C23A' }
      },
      {
        name: '失败',
        type: 'line',
        data: failData,
        smooth: true,
        itemStyle: { color: '#F56C6C' }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 渲染错误类型图表
function renderErrorChart() {
  if (!errorChart.value || !logStats.value.errors.length) {
    return
  }
  
  const chart = echarts.init(errorChart.value)
  const data = logStats.value.errors.map(item => ({
    name: item.error_code || '未知错误',
    value: item.count
  }))
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '错误类型',
        type: 'pie',
        radius: '50%',
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

onMounted(() => {
  loadLicenseStats()
  loadLogStats()
})
</script>

<style scoped lang="scss">
.mb-20 {
  margin-bottom: 20px;
}

.stat-card-wrapper {
  cursor: pointer;
  transition: transform 0.3s;
  
  &:hover {
    transform: translateY(-5px);
  }
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 20px;

  .stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;

    &.primary {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    &.success {
      background: linear-gradient(135deg, #5cb85c 0%, #4cae4c 100%);
    }

    &.warning {
      background: linear-gradient(135deg, #f0ad4e 0%, #ec971f 100%);
    }

    &.danger {
      background: linear-gradient(135deg, #d9534f 0%, #c9302c 100%);
    }
  }

  .stat-content {
    flex: 1;

    .stat-title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 8px;
    }

    .stat-value {
      font-size: 28px;
      font-weight: bold;
      color: #303133;
    }
  }
}

.mini-stat {
  text-align: center;
  padding: 10px 0;
  
  .label {
    font-size: 12px;
    color: #909399;
    margin-bottom: 8px;
    
    &.success {
      color: #67C23A;
    }
    
    &.danger {
      color: #F56C6C;
    }
    
    &.warning {
      color: #E6A23C;
    }
  }
  
  .value {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    
    &.success {
      color: #67C23A;
    }
    
    &.danger {
      color: #F56C6C;
    }
    
    &.warning {
      color: #E6A23C;
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}
</style>
